package cn.mesmile.juc.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zb
 * @date 2021/8/15 15:23
 * @Description
 */
public class LockTest {

    public static void main(String[] args) {
        Window w = new Window();

        Thread t1 = new Thread(w);
        Thread t2 = new Thread(w);
        Thread t3 = new Thread(w);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }

}

class Window implements Runnable {
    /** 定义一百张票 */
    private int ticket = 100;
    /** 1.实例化锁 */
    private ReentrantLock lock = new ReentrantLock(true);

    @Override
    public void run() {

        while (true) {
            if (ticket > 0) {
                //2.调用锁定方法lock
                lock.lock();
                try {
                    Thread.sleep(10);
                    if (ticket > 0){
                        System.out.println(Thread.currentThread().getName() + "售出第" + ticket + "张票");
                        ticket--;
                    }
//                    if (ticket == 50){
//                        //   线程不会停下来
//                        throw new RuntimeException("抛出异常");
//                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }else {
                break;
            }
        }
    }

}